from rest_framework import serializers

from system.serializer.menuserializer import MenuSerializer
from system import models
from system.serializer.dept import DeptSerializer


class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Roles
        fields = '__all__'


class RoleAllSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Roles
        fields = ['createTime', 'description', 'name', 'dataScope', 'depts', 'id',
                  'level', 'menus', 'updateBy', 'updateTime']

    createTime = serializers.SerializerMethodField()
    updateTime = serializers.SerializerMethodField()

    def get_createTime(self, obj):
        return obj.create_time

    def get_updateTime(self, obj):
        return obj.update_time

    dataScope = serializers.SerializerMethodField()

    def get_dataScope(self, obj):
        return obj.data_scope

    updateBy = serializers.SerializerMethodField()

    def get_updateBy(self, obj):
        return obj.update_by

    menus = MenuSerializer(many=True)
    # menus = serializers.SerializerMethodField()
    # def get_menus(self, obj):
    #     for menu in obj.menu.all():
    #         return {
    #             'cache': menu.cache,
    #             'component': menu.component,
    #             'componentName': menu.name,
    #             'createTime':
    #         }
    depts = DeptSerializer(many=True)

    def get_depts(self, obj):
        role_list = obj.roles_set.all()
        for role in role_list:
            if not role.dept.all():
                return []


class CreateRoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Roles
        fields = ['dataScope', 'depts', 'createBy', 'createTime', 'description', 'id', 'level', 'menus',
                  'name', 'updateBy', 'updateTime']

    dataScope = serializers.CharField(read_only=True)
    depts = serializers.CharField(read_only=True)
    menus = serializers.CharField(read_only=True)
    createBy = serializers.CharField(read_only=True)
    createTime = serializers.CharField(read_only=True)
    updateBy = serializers.CharField(read_only=True)
    updateTime = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['create_by'] = request.user.username
        attrs['depts'] = request.data.get('depts')
        attrs['data_scope'] = request.data.get('dataScope')
        return attrs

    def create(self, validated_data):
        """
        1. 拿到部门id
        2. 分析部门id,那个有子部门,如果有子部门,则把这个部门的所有子部门一起做多对多表关系
        :param validated_data:
        :return:
        """
        depts_list = validated_data.pop('depts')
        role = models.Roles.objects.create(**validated_data)
        for dept_id in depts_list:
            dept = models.Dept.objects.filter(pk=dept_id.get('id')).first()
            if dept.sub_count:  # 有子部门的
                for sun_dept in models.Dept.objects.filter(pid=dept):  # 当前部门下的所有子部门
                    role.depts.add(sun_dept.pk)
                    role.save()
            return role


class UpdateRoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Roles
        fields = ['createTime', 'dataScope', 'depts', 'description', 'id', 'level', 'menus', 'name',
                  'updateBy', 'updateTime']
    createTime = serializers.CharField(read_only=True)
    dataScope = serializers.CharField(read_only=True)
    depts = serializers.CharField(read_only=True)
    menus = serializers.CharField(read_only=True)
    updateBy = serializers.CharField(read_only=True)
    updateTime = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['update_by'] = request.user.username
        attrs['data_scope'] = request.data.get('dataScope')
        return attrs

    def update(self, instance, validated_data):
        """
        1. 拿到部门id
        2. 分析部门id,那个有子部门,如果有子部门,则把这个部门的所有子部门一起做多对多表关系
        :param instance:
        :param validated_data:
        :return:
        """
        l = []
        request = self.context.get('request')
        depts_list = request.data.get('depts')
        models.Roles.objects.filter(pk=request.data.get('id')).update(**validated_data)
        role = models.Roles.objects.filter(pk=request.data.get('id')).first()
        for dept_id in depts_list:
            dept = models.Dept.objects.filter(pk=dept_id.get('id')).first()
            l.append(dept)
            if dept.sub_count:  # 有子部门的
                for sun_dept in models.Dept.objects.filter(pid=dept):  # 当前部门下的所有子部门
                    l.append(sun_dept)
            role.depts.clear()
            role.depts.set(l)
        return role


class UpdateRoleMenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Roles
        fields = ['id', 'menus']

    menus = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['menus'] = request.data.get('menus')
        return attrs


    def update(self, instance, validated_data):
        l = []
        for i in validated_data['menus']:
            l.append(i.get('id'))
        instance.menus.set(l)
        return models.Roles.objects.filter(pk=self.context.get('request').data.get('id'))